﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.tanlingyun.helper
{
    public class JsonHelper
    {
        /// <summary>
        /// json序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// dictionary序列成json字符串
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static string Serialize(IDictionary<string,string> dict)
        {
            IList<string> jsonList = new List<string>();
            foreach (KeyValuePair<string,string> keypair in dict)
            {
                jsonList.Add("\"" + keypair.Key + "\":\""+keypair.Value+"\"");
            }
            return "{" + string.Join(",", jsonList) + "}";
        }

        /// <summary>
        /// json反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }
    }
}
